package com.xymtop.api.controller;

import com.google.code.kaptcha.Producer;
import com.xymtop.api.service.EmailService;
import com.xymtop.api.utils.JsonResoult;
import com.xymtop.api.utils.MyCookie;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @ClassName : CaptchaController
 * @Description : 验证码接口控制器
 * @Author : 肖叶茂
 * @Date: 2022/12/4  10:14
 */
@RestController
@RequestMapping("captcha")
public class CaptchaController {
    @Autowired
    private Producer kaptchaProducer;
    @Autowired
    private EmailService emailService;

    @RequestMapping("getCaptcha")
    public  void getCaptcha(HttpServletResponse response){
            //    生成验证码
        int x=(int)(Math.random()*10);
        int y=(int)(Math.random()*10);

            String text= String.valueOf(x)+" + "+String.valueOf(y)+" = ?";
            //    生成验证码图片
            BufferedImage image = kaptchaProducer.createImage(text);

        MyCookie.setCookie(response,"captcha",String.valueOf(x+y));
            //    将图片输出到前端(图片+格式)
            response.setContentType("image/png");
            try {
                ServletOutputStream outputStream = response.getOutputStream();
                ImageIO.write(image, "png", outputStream);
            } catch (IOException e) {
                System.out.println("响应验证码失败");
            }
    }

    @RequestMapping("getEmailCaptcha")
    public JsonResoult<String> getEmailCaptcha(HttpServletResponse response,String email){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        emailService.sendSimpleMail(email,"验证码","您的验证码为: "+str.toString());
        MyCookie.setCookie(response,"captcha",str.toString());
        return new JsonResoult<>(200);
    }
}
